
package l1j.server.server.clientpackets;


import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.假人系統.DummyThread;
import l1j.server.echo.ClientThread;
import l1j.server.server.datatables.BuddyTable;
import l1j.server.server.datatables.CharacterTable;
import l1j.server.server.model.L1Buddy;
import l1j.server.server.model.Instance.L1DummyInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.serverpackets.S_ServerMessage;
import l1j.server.server.serverpackets.S_SystemMessage;
import l1j.server.server.templates.L1CharName;

public class C_AddBuddy extends ClientBasePacket {

	private static final String C_ADD_BUDDY = "[C] C_AddBuddy";
	private static final Logger _log = Logger.getLogger(C_AddBuddy.class.getName());
	@Override
	public String getType() {
		return C_ADD_BUDDY;
	}


	@Override
	public void start(final byte[] decrypt, final ClientThread client) {
		try {
			// 資料載入
			this.read(decrypt);
		final L1PcInstance pc = client.getActiveChar();
		final BuddyTable buddyTable = BuddyTable.getInstance();
		final L1Buddy buddyList = buddyTable.getBuddyTable(pc.getId());
		final String charName = this.readS();
		if(charName == null){
			return;
		}
		if (charName.equalsIgnoreCase(pc.getName())) {
			return;
		} else if (buddyList.containsName(charName)) {
			pc.sendPackets(new S_ServerMessage(1052, charName)); // %s
			// は既に登録されています。
			return;
		}
		if(DummyThread.getInstance().checkNameOnline(charName)){
			L1DummyInstance temp = DummyThread.getInstance().getDummyTemp(charName);
			buddyList.add(temp.getId(), charName);
			return;
		}

		for (final L1CharName cn : CharacterTable.getInstance().getCharNameList()) {
			if (charName.equalsIgnoreCase(cn.getName())) {
				//opqlo 不允許玩家加入GM為好友
				if(cn.getIsGM()){
					pc.sendPackets(new S_SystemMessage("無法加入GM權限角色，任何疑問請洽詢線上客服。"));
					return;
				}
				//opqlo 不允許玩家加入GM為好友
				final int objId = cn.getId();
				final String name = cn.getName();
				buddyList.add(objId, name);
				buddyTable.addBuddy(pc.getId(), objId, name);
				return;
			}
		}
		pc.sendPackets(new S_ServerMessage(109, charName)); // %0という名前の人はいません。
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);

		} finally {
			this.over();
		}
		}
}
